package com.shengchang.hu.supervision.UI;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.posapi.PosApi;
import android.posapi.PrintQueue;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.shengchang.hu.supervision.Application.App;
import com.shengchang.hu.supervision.R;
import com.shengchang.hu.supervision.ToolBar.InBoundBar;
import com.shengchang.hu.supervision.Utils.Contants;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.InputMismatchException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ChuKuBlueActivity extends BaseActivity implements View.OnClickListener {


    InBoundBar inboundbar;
    TextView yunsongren;

    EditText jiaoyanEdit;
    EditText weightEdit;
    Button printcode;
    private PosApi mPosSDK = null;
    private PrintQueue mPrintQueue = null;
    private String departmentid;
    /*扫描*/
    MediaPlayer player;
    private byte mGpioPower = 0x1E;// PB14
    private byte mGpioTrig = 0x29;// PC9
    boolean isCanPrint = true;
private  String  Code;
    JSONArray array;

    private ScanBroadcastReceiver scanBroadcastReceiver;
    OkHttpClient okHttpClient = new OkHttpClient();
    private static  final  String Terminal_outRubbishInBox=Contants.Terminal_outRubbishInBox;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chu_ku_blue);
        inboundbar=findViewById(R.id.inboundbar);
        yunsongren=findViewById(R.id.yunsongren);
        jiaoyanEdit=findViewById(R.id.jiaoyan_edit);
        weightEdit=findViewById(R.id.weight_edit);
        printcode=findViewById(R.id.printcode);
        printcode.setOnClickListener(this);
        ConnectInent();
        initPos();
    }

    private void initScan() {
        //注册获取扫描信息的广播接收器
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(PosApi.ACTION_POS_COMM_STATUS);
        registerReceiver(receiver, mFilter);
        // 物理扫描键按下时候会有动作为ismart.intent.scandown的广播发出，可监听该广播实现触发扫描动作
        scanBroadcastReceiver = new ScanBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("ismart.intent.scandown");
        this.registerReceiver(scanBroadcastReceiver, intentFilter);

        // 扫描提示音
        player = MediaPlayer.create(getApplicationContext(),
                R.raw.beep);

    }

    @Override
    protected void onResume() {
        super.onResume();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            initScan();


                        }
                    });
                } catch (InputMismatchException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    /**
     * 物理SCAN按键监听
     */
    boolean isScan = false;

    public void onClick(View view) {
        switch (view.getId()){
            case R.id.printcode:
              if (TextUtils.isEmpty(jiaoyanEdit.getText().toString())){
                  showShortToast("请扫码");
              }else
                  if (TextUtils.isEmpty(weightEdit.getText().toString())){
                  showShortToast("请输入重量");

              }else{
                  showProgressDialog();
                  CHUKU_Request();
                  }
                break;
        }

    }

    class ScanBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            //监听到SCAN按键按下广播，执行扫描

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                ScanDomn();

                            }
                        });
                    } catch (InputMismatchException e) {
                        e.printStackTrace();
                    }

                }
            }).start();


        }
    }

    private void initPos() {
        // 获取PosApi实例
        mPosSDK = PosApi.getInstance(this);
        // 根据型号进行初始化mPosApi类
        if (Build.MODEL.contains("LTE")
                || Build.DISPLAY.contains("3508")
                || Build.DISPLAY.contains("403")
                || Build.DISPLAY.contains("35S09")) {
            mPosSDK.initPosDev("ima35s09");
        } else if (Build.MODEL.contains("5501")) {
            mPosSDK.initPosDev("ima35s12");
        } else {
            mPosSDK.initPosDev(PosApi.PRODUCT_MODEL_IMA80M01);
        }

        //监听初始化回调结果
        mPosSDK.setOnComEventListener(mCommEventListener);

    }

    /**
     * 初始化
     */
    PosApi.OnCommEventListener mCommEventListener = new PosApi.OnCommEventListener() {
        @Override
        public void onCommState(int cmdFlag, int state, byte[] resp, int respLen) {
            // TODO Auto-generated method stub
            switch (cmdFlag) {
                case PosApi.POS_INIT:
                    if (state == PosApi.COMM_STATUS_SUCCESS) {
                        Toast.makeText(getApplicationContext(), "设备初始化成功",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getApplicationContext(), "设备初始化失败",
                                Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        }
    };

    private void ConnectInent() {
        Intent intent = getIntent();
        String ufhdata = intent.getStringExtra("Ufhdata");
        departmentid = intent.getStringExtra("departmentid");
        Log.d("departmentid", departmentid);
        yunsongren.setText(ufhdata);

    }
    /**
     * 执行扫描，扫描后的结果会通过action为PosApi.ACTION_POS_COMM_STATUS的广播发回
     */
    public void ScanDomn() {
        if (!isScan) {
            mPosSDK.gpioControl(mGpioTrig, 0, 0);
            isScan = true;
            handler.removeCallbacks(run);
            // 3秒后还没有扫描到信息则强制关闭扫描头
            handler.postDelayed(run, 200);
        } else {
            mPosSDK.gpioControl(mGpioTrig, 0, 1);
            mPosSDK.gpioControl(mGpioTrig, 0, 0);
            isScan = true;
            handler.removeCallbacks(run);
            // 3秒后还没有扫描到信息则强制关闭扫描头
            handler.postDelayed(run, 200);
        }
    }

    Handler handler = new Handler();
    Runnable run = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            // 强制关闭扫描头
            mPosSDK.gpioControl(mGpioTrig, 0, 1);
            isScan = false;
        }
    };
    private void CHUKU_Request() {
        JSONArray jsonArray=new JSONArray();
        JSONObject obj1=new JSONObject();
        try {
            obj1.put("boxCode",jiaoyanEdit.getText().toString());
            obj1.put("weight",weightEdit.getText().toString());
            array = jsonArray.put(obj1);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody formBody = new FormBody.Builder()
                .add("id",App.getApp().getToken())
                .add("boxes", String.valueOf(array))
                .add("transportId",departmentid)
                .add("handoverName",yunsongren.getText().toString())
                .build();
        Request request = new Request.Builder()
                .url(Terminal_outRubbishInBox)
                .post(formBody)
                .build();
        Log.d("Cntralized_API",Terminal_outRubbishInBox+"?id="+App.getApp().getToken()
                +"&boxes="+String.valueOf(array)
                +"&transportId="+departmentid
                +"&handoverName="+yunsongren.getText().toString());
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                dismissProgressDialog();
                                // 放在UI线程弹Toast
                                showLongToast("请求失败，请确认网络");
                            }				});				//此处会发生异常//
                    }		}).start();

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String  chukuloginstr=response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        chukuResPonse(chukuloginstr);
                    }
                });

            }
        });

    }

    private void chukuResPonse(String chukuloginstr) {
        try {
            JSONObject  Json=new JSONObject(chukuloginstr);
            String message = Json.getString("message");
            if (message.equals("20004")){
                dismissProgressDialog();
                showShortToast("网络异常");
            }else if (message.equals("20005")){
                dismissProgressDialog();
                showShortToast("出库成功");
                weightEdit.getText().clear();
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    /**
     * 扫描信息获取
     */
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action = intent.getAction();
            if (action.equalsIgnoreCase(PosApi.ACTION_POS_COMM_STATUS)) {
                // 串口标志判断
                int cmdFlag = intent.getIntExtra(PosApi.KEY_CMD_FLAG, -1);
                // 获取串口返回的字节数组
                byte[] buffer = intent
                        .getByteArrayExtra(PosApi.KEY_CMD_DATA_BUFFER);
                switch (cmdFlag) {
                    // 如果为扫描数据返回串口
                    case PosApi.POS_EXPAND_SERIAL3:
                        if (buffer == null)
                            return;
                        try {
                            // 将字节数组转成字符串
                            final String str = new String(buffer, "UTF-8");
                            // 开启提示音，提示客户条码或者二维码已经被扫到
                            player.start();
                            if (!TextUtils.isEmpty(str)){
                               jiaoyanEdit.setText(str);
                            }else {
                                showShortToast("请先扫码");
                            }


                            } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        break;
                }
                // 扫描完本次后清空，以便下次扫描
                buffer = null;
            }
        }
    };


    @Override
    protected void onPause() {
        super.onPause();
        // 注销获取扫描数据的广播
        unregisterReceiver(receiver);
        // 注销物理SCAN按键的接收广播
        unregisterReceiver(scanBroadcastReceiver);

        if (mPrintQueue != null) {
            // 打印队列关闭
            mPrintQueue.close();
        }

        // 关闭下层串口以及打印机
        mPosSDK.closeDev();

    }

    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();


    }
    @Override
    public void onBackPressed() {
        finish();
    }
}
